<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { CirclePlus, Delete, EditPen, Search } from '@element-plus/icons-vue';
import { register, queryUser, deleteUser, updateUser } from '@/api/user.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { loginStore } from "@/stores/loginStore.js";

const store = loginStore();

// 用户列表数据
const tableData = ref([]);
// 搜索关键字
const searchKeyword = ref('');

// 获取用户列表
const getuserlist = async () => {
    await queryUser({}).then(res => {
        tableData.value = res.data.detail.data;
    });
}

// 页面初始化，获取用户列表
onMounted(async () => {
    getuserlist();
})

// 分页
// 当前页码，初始值为1
const currentPage = ref(1)
// 每页显示的记录数，初始值为10
const pagesize = ref(10)

/**
 * 处理每页显示记录数变化的函数
 * @param {number} val - 新的每页显示记录数
 */
const handleSizeChange = (val) => {
    // 更新每页显示的记录数
    pagesize.value = val;
}

/**
 * 处理当前页码变化的函数
 * @param {number} val - 新的当前页码
 */
const handleCurrentChange = (val) => {
    // 更新当前页码
    currentPage.value = val;
}

/**
 * 处理当前选中行变化的函数
 * @param {object} val - 当前选中行
 */
const currentRow = ref();
const handleCurrentRowChange = (val) => {
    currentRow.value = val;
    console.log(currentRow.value);
}

// 筛选后的用户列表数据
const filteredTableData = computed(() => {
    return tableData.value.filter(
        (item) =>
            // 检查登录名、用户名称是否包含搜索关键字
            // 如果搜索关键字为空，则返回所有记录
            !searchKeyword.value || item.login_name.toLowerCase().includes(searchKeyword.value.toLowerCase()) || 
                item.user_name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
                item.phonenumber.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
                item.user_role.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
                item.status.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
                item.remark.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
});

// 注册用户弹窗是否显示
const registerDialogVisible = ref(false)
// 编辑用户弹窗是否显示
const updateDialogVisible = ref(false)

// 用户表单数据   1sdfa33
const formData = ref({
    login_name: '1sdfa',
    user_name: '1adfa',
    password: 'admin123',
    phonenumber: '15257469828',
    user_role: '01',
    status: '1',
    remark: '',
    create_by: store.login_name,
    update_by: store.login_name
});

// 更新用户表单数据，数据结构和formData一致
// 用于更新用户时，将用户信息填充到表单中
const updateFormData = ref({
    login_name: '',
    user_name: '',
    phonenumber: '',
    user_role: '',
    status: '',
    remark: '',
    update_by: store.login_name
})

// 用户角色
const roles = [
    {
        label: '管理员',
        value: '01',
    },
    {
        label: '普通用户',
        value: '02',
    }
]

// 用户角色格式化
const roleformat = (row, column, cellValue) => {
    if (cellValue === '01') {
        return '管理员';
    } else if (cellValue === '02') {
        return '普通用户';
    } else {
        return '';
    }
}

// 用户状态格式化
const statusformat = (row, column, cellValue) => {
    if (cellValue === '1') {
        return '启用';
    } else if (cellValue === '0') {
        return '禁用';
    } else {
        return '';
    }
}

// 表单引用
const formRegisterRef = ref();
const formUpdateRef = ref();
// 表格引用
const tableRef = ref();

// 表单验证规则
const rules = {
    login_name: [
        { required: true, message: '请输入登录名', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9]+$/, message: '登录名只能包含字母和数字', trigger: 'blur' }
    ],
    user_name: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名称长度在2-20个字符之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
    ],
    phonenumber: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    user_role: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
    ]
};

// 注册用户提交
const handleRegisterSubmit = async () => {
    if (!formRegisterRef.value) return;

    // 表单验证
    await formRegisterRef.value.validate((valid) => {
        if (valid) {
            // 调用接口，创建新账号
            register(formData.value).then(res => {
                // 注册返回信息提示
                // 202: 注册失败
                // 200: 注册成功
                if (res.data.detail.status === '202') {
                    ElMessage.error(res.data.detail.message);
                    return;
                } else if (res.data.detail.status === '200') {
                    ElMessage.success(res.data.detail.message);
                    // 重新获取用户列表,刷新table数据
                    // getuserlist();
                    // 将新增数据添加到tableData中
                    tableData.value.push({ ...formData.value });
                    // 关闭弹窗
                    closeDialog("register");
                }
            })
        } else {
            ElMessage.error('正确填写信息');
        }
    });
}

const updateuser = () => {
    // 获取选中的login_name
    const selecteduser = tableRef.value.getSelectionRows();

    // 判断是否选中用户
    if (selecteduser.length === 0) {
        ElMessage.error('请选择要编辑的用户');
        return;
    }
    // 判断是否选中多个用户
    if (selecteduser.length > 1) {
        ElMessage.error('只能选择一个用户进行编辑');
        return;
    }
    // 将选中用户的信息填充到表单中
    for (let key in updateFormData.value) {
        updateFormData.value[key] = selecteduser[0][key];
    }
    // 弹出编辑用户弹窗
    updateDialogVisible.value = true;
}

// 编辑用户提交
const handleUpdateSubmit = async () => {
    if (!formUpdateRef.value) return;

    await formUpdateRef.value.validate((valid) => {
        if (valid) {
            // 调用接口，更新账号信息
            updateUser(updateFormData.value).then(res => {
                // 更新返回信息提示
                // 202: 更新失败
                // 200: 更新成功
                if (res.data.detail.status === '202') {
                    ElMessage.error(res.data.detail.message);
                    return;
                } else if (res.data.detail.status === '200') {
                    ElMessage.success(res.data.detail.message);
                    // 重新获取用户列表,刷新table数据
                    getuserlist();
                    // 关闭弹窗
                    closeDialog("update");
                }
            });
        } else {
            ElMessage.error('验证失败');
        }
    });
}

// 删除用户
const deleteuser = async () => {
    // 获取选中的login_name
    const selecteduser = tableRef.value.getSelectionRows();
    if (selecteduser.length === 0) {
        ElMessage.error('请选择要删除的用户');
        return;
    }
    // 弹出确认框
    ElMessageBox.confirm(
        `将永久删除${selecteduser.length}个用户账号, 是否继续?`,
        '是否删除',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }
    ).then(async () => {
        // 调用接口，删除用户
        for (let user of selecteduser) {
            await deleteUser({ "login_name": user.login_name });
        }
        ElMessage({
            type: 'success',
            message: '删除成功',
        })
        // 重新获取用户列表,刷新table数据
        getuserlist();
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
        })
    })
}

// 根据val值关闭对应的弹窗
const closeDialog = (val) => {
    if (val === 'register') {
        formRegisterRef.value?.resetFields();
        registerDialogVisible.value = false;
    } else {
        formUpdateRef.value?.resetFields();
        updateDialogVisible.value = false;
    }
};
</script>

<template>
    <!-- 页面内容 -->
    <div class="w-full h-full">
        <el-card>
            <template #header>
                <div class="card-header flex items-center justify-between">
                    <div>
                        <el-button type="primary" size="small" :icon="CirclePlus"
                            @click="registerDialogVisible = true">新增</el-button>
                        <el-button size="small" :icon="EditPen" @click="updateuser">编辑</el-button>
                        <el-button type="danger" size="small" :icon="Delete" @click="deleteuser">删除</el-button>
                    </div>
                    <div class="flex items-center">
                        <div class="relative">
                            <input v-model="searchKeyword" type="text"
                                class="w-64 rounded-lg border border-gray-200 py-1 pl-10 pr-10 text-sm focus:border-blue-500 focus:outline-none"
                                placeholder="请输入关键字搜索" />
                            <el-icon class="ml-4 text-gray-400">
                                <Search />
                            </el-icon>
                        </div>
                    </div>
                </div>
            </template>
            <el-table ref="tableRef"
                :data="filteredTableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)" class="w-full"
                highlight-current-row @selection-change="handleCurrentRowChange">
                <el-table-column type="selection" width="55" />
                <el-table-column property="login_name" label="登录名" align="center" width="120" show-overflow-tooltip />
                <el-table-column property="user_name" label="用户名称" align="center" show-overflow-tooltip />
                <el-table-column property="phonenumber" label="联系电话" align="center" show-overflow-tooltip />
                <el-table-column property="user_role" label="用户角色" align="center" show-overflow-tooltip :formatter="roleformat" />
                <el-table-column property="status" label="账号状态" align="center" show-overflow-tooltip :formatter="statusformat" />
                <el-table-column property="remark" label="备注" align="center" show-overflow-tooltip />
            </el-table>
            <div class="flex justify-start mt-6">
                <el-pagination :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumpe"
                    :total="filteredTableData.length" :page-size="pagesize" :current-page="currentPage" hide-on-single-page
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
    <!-- 注册用户弹窗 -->
    <el-dialog v-model="registerDialogVisible" width="400" center destroy-on-close draggable title="创建新账号">
        <div class="inset-0 flex items-center justify-center">
            <div class="rounded-lg w-[480px] p-4">
                <!-- 表单区域 -->
                <el-form ref="formRegisterRef" :model="formData" label-position="top" :rules="rules">
                    <!-- 登录名 -->
                    <el-form-item label="登录名" prop="login_name" required>
                        <el-input v-model="formData.login_name" placeholder="请输入字母数字组合的登录名" class="h-8" />
                    </el-form-item>

                    <!-- 用户名称 -->
                    <el-form-item label="用户名称" prop="user_name" required>
                        <el-input v-model="formData.user_name" placeholder="请输入用户名称" class="h-8" />
                    </el-form-item>

                    <!-- 密码 -->
                    <el-form-item label="密码" prop="password" required>
                        <el-input v-model="formData.password" placeholder="请输入密码" class="h-8" show-password />
                    </el-form-item>

                    <!-- 手机号码 -->
                    <el-form-item label="手机号码" prop="phonenumber" required>
                        <el-input v-model="formData.phonenumber" placeholder="请输入11位手机号码" maxlength="11" class="h-8" />
                    </el-form-item>

                    <!-- 用户角色 -->
                    <el-form-item label="用户角色" prop="user_role" required>
                        <el-select v-model="formData.user_role" placeholder="请选择用户角色" class="w-full h-8">
                            <el-option v-for="item in roles" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <!-- 备注 -->
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="formData.remark" placeholder="请输入备注" class="h-12" />
                    </el-form-item>

                    <!-- 账号状态 -->
                    <el-form-item label="账号状态">
                        <el-switch v-model="formData.status" active-text="启用" active-value="1" inactive-text="禁用"
                            inactive-value="0" />
                    </el-form-item>

                    <!-- 按钮组 -->
                    <div class="flex gap-4 mt-8">
                        <el-button type="primary" class="flex-1 !rounded-button whitespace-nowrap"
                            @click="handleRegisterSubmit">
                            确认创建
                        </el-button>
                        <el-button class="flex-1 !rounded-button whitespace-nowrap" @click="closeDialog('register')">
                            取消
                        </el-button>
                    </div>
                </el-form>
            </div>
        </div>
    </el-dialog>
    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="updateDialogVisible" width="400" center destroy-on-close draggable title="更新账号信息">
        <div class="inset-0 flex items-center justify-center">
            <div class="rounded-lg w-[480px] p-4">
                <!-- 表单区域 -->
                <el-form ref="formUpdateRef" :model="updateFormData" label-position="top" :rules="rules">
                    <!-- 登录名 -->
                    <el-form-item label="登录名" prop="login_name" required>
                        <el-input v-model="updateFormData.login_name" placeholder="请输入字母数字组合的登录名" class="h-8"
                            disabled />
                    </el-form-item>

                    <!-- 用户名称 -->
                    <el-form-item label="用户名称" prop="user_name" required>
                        <el-input v-model="updateFormData.user_name" placeholder="请输入用户名称" class="h-8" disabled />
                    </el-form-item>

                    <!-- 手机号码 -->
                    <el-form-item label="手机号码" prop="phonenumber" required>
                        <el-input v-model="updateFormData.phonenumber" placeholder="请输入11位手机号码" maxlength="11"
                            class="h-8" />
                    </el-form-item>

                    <!-- 用户角色 -->
                    <el-form-item label="用户角色" prop="user_role" required>
                        <el-select v-model="updateFormData.user_role" placeholder="请选择用户角色" class="w-full h-8">
                            <el-option v-for="item in roles" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <!-- 备注 -->
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="updateFormData.remark" placeholder="请输入备注" class="h-12" />
                    </el-form-item>

                    <!-- 账号状态 -->
                    <el-form-item label="账号状态">
                        <el-switch v-model="updateFormData.status" active-text="启用" active-value="1" inactive-text="禁用"
                            inactive-value="0" />
                    </el-form-item>

                    <!-- 按钮组 -->
                    <div class="flex gap-4 mt-8">
                        <el-button type="primary" class="flex-1 !rounded-button whitespace-nowrap"
                            @click="handleUpdateSubmit">
                            确认更新
                        </el-button>
                        <el-button class="flex-1 !rounded-button whitespace-nowrap" @click="closeDialog('update')">
                            取消
                        </el-button>
                    </div>
                </el-form>
            </div>
        </div>
    </el-dialog>
</template>



<style scoped></style>